package com.powergisol.gis.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.powergisol.gis.entity.FileDocument;
import com.powergisol.gis.service.RemoteService;
import com.powergisol.gis.util.PropertyUtil;
import com.powergisol.gis.vo.TabServiceVo;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.Date;



@Service
public class RemoteServiceImpl implements RemoteService {
    private static Logger logger = LoggerFactory.getLogger(RemoteServiceImpl.class);
    @Autowired
    private GridFsOperations operations;
    @Autowired
    private GridFSBucket gridFSBucket;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Value("${collectionName}")
    private String collectionName;
//    @Value("${file-url}")
//    private String fileUrl;


    @Override
    public ResponseEntity getServiceChunks(String serviceName, String uniqueFlag) {
        String md5 = SecureUtil.md5(uniqueFlag+serviceName);
        Query query = new Query().addCriteria(Criteria.where("md5").is(md5));
        FileDocument fileDocument = mongoTemplate.findOne(query , FileDocument.class , collectionName);
        JSONObject json =new JSONObject();
        if(null != fileDocument){
            String userDir = System.getProperty("user.dir");
            userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
            String attachmentUrlSet = userDir+File.separator+"serviceData"+
                    File.separator+"chunks"+File.separator+"shp"+File.separator+md5+"."+fileDocument.getSuffix();
            //写入文件返回路径
            File file = new File(attachmentUrlSet);
            if(file.exists()){
                json.put("fileUrl",attachmentUrlSet);
                return ResponseEntity.ok(json);
            }else{
                file.getParentFile().mkdirs();
                GridFSDownloadStream stream = null;
                try {
                    GridFSFile gridFSFile = operations.findOne(new Query(Criteria.where("filename").is(md5)));
                    ObjectId objectId = gridFSFile.getObjectId();
                    stream = gridFSBucket.openDownloadStream(objectId);
                    /** gridfs file */
                    GridFSFile gridFSFile1 = stream.getGridFSFile();
                    File fileObj = new File(attachmentUrlSet);
                    OutputStream out = new FileOutputStream(fileObj);

                    /** chunk size */
                    int size = gridFSFile1.getChunkSize();
                    Long len = gridFSFile1.getLength();
                    /** loop time */
                    BigDecimal num = new BigDecimal(len).divide(new BigDecimal(size),0,BigDecimal.ROUND_UP);
                    Integer cnt = Integer.valueOf(num.toString());
                    byte[] bts = new byte[size];
                    try {
                        while (cnt-- > 0) {
                            int tmp = stream.read(bts);
                            out.write(bts, 0, tmp);
                        }
                        out.flush();
                        out.close();
                        json.put("fileUrl",attachmentUrlSet);
                        return ResponseEntity.ok(json);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) stream.close();
                }
            }
        }
        json.put("code",404);
        json.put("msg","文件不存在");
        return ResponseEntity.ok(json);
    }

    @Override
    public ResponseEntity saveServiceChunks(String serviceName, String uniqueFlag, InputStream in) {
//        TabServiceVo vo = new TabServiceVo();
//        vo.setName(serviceName);
//        TabService tabService = tabServiceMapper.getTabServiceCondition(vo);
//        String suffix = uniqueFlag.substring(uniqueFlag.lastIndexOf(".")+1);
//        try {
//            //if(null == in){
//            in = new FileInputStream(new File("E:\\gd_sz_xzqh.sld"));
//            //}
//            String filename = SecureUtil.md5(uniqueFlag+serviceName);
//            FileDocument fileDocument = new FileDocument();
//            fileDocument.setServiceName(tabService.getUuid());
//            fileDocument.setUploadDate(new Date());
//            fileDocument.setMd5(filename);
//            fileDocument.setSuffix(suffix);
//            // fileDocument.setName(filename);
//            //设置chunks长度为358400字节，如果文件过大则创建新的分块
//            // 自定义的数据放在metadata里
//            GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(358400);
//            ObjectId fileId = gridFSBucket.uploadFromStream(filename, in, options);
//            fileDocument.setGridfsId(fileId.toString());
//            mongoTemplate.save(fileDocument , collectionName);
//            return ResponseEntity.ok("保存成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("保存失败");
//        }
        return null;
    }

}
